package com.yangye.otherdemo.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.junit.Test;

import java.net.InetSocketAddress;

public class MyNettyDemo {


	@Test
	public void nettyServer() {
		NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();// 默认逻辑核心数量*2

		ServerBootstrap b = new ServerBootstrap();
		try {
			b.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel socketChannel) throws Exception {
							ChannelPipeline p = socketChannel.pipeline();
							p.addLast(new MyInHandler());
						}
					});
			ChannelFuture bind = b.bind(9090);
			// 等待服务器启动成功
			bind.sync();
			System.out.println("服务器启动成功...");

			// 等待服务端断开连接
			bind.channel().closeFuture().sync();
			System.out.println("服务端关闭...");


		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	@Test
	public void nettyClient() {
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();
		Bootstrap b = new Bootstrap();
		try {
			b.group(workerGroup)
					.channel(NioSocketChannel.class)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel socketChannel) throws Exception {
							ChannelPipeline p = socketChannel.pipeline();
							p.addLast(new MyInHandler());
						}
					});
			ChannelFuture connect = b.connect(new InetSocketAddress("192.168.214.1", 9090));
			// 等待连接成功
			connect.sync();
			System.out.println("连接服务器成功...");
			Channel client = connect.channel();
			// 等待客户端断开连接
			client.closeFuture().sync();
			System.out.println("客户端断开连接...");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
